package com.lehe.controller.admin;

import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import com.lehe.common.utils.StringUtil;
import com.lehe.entry.*;
import com.lehe.service.impl.AdminUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.lehe.dao.PayRecordDao;
import com.lehe.dao.UserInfoDao;
import com.lehe.dao.UserManagerDao;
import com.lehe.entry.page.PageDto;
import com.lehe.service.impl.AdminFeeReportService;

@RequestMapping("admin/finance")
@Controller
public class FinanceController  extends BaseAdminController{

	@Autowired
	private UserManagerDao userManagerDao;
	
	@Autowired
	private UserInfoDao userInfoDao;
	
	@Autowired
	AdminFeeReportService adminFeeReportService;

	@Autowired
	private PayRecordDao payRecordDao;
	@Autowired
	AdminUserService adminUserService;
	
	@RequestMapping("userfinance")
	public String userfinance(Model m){
		return "admin/finance/info";
	}
	
	@RequestMapping("score")
	public String score(Model m){
		List<Long> ids = this.getGameUserIds();
		
		if(ids != null && !ids.isEmpty()){
			m.addAttribute("ids",ids);
		}
		return "admin/finance/score/score";
	}
	
	@RequestMapping("scoreList")
	public String scoreList(String userId,String sd,String ed,Model m){
 		List<Long> userIds = null;
		if(StringUtil.isBlank(userId)){
			m.addAttribute("adminUser",this.getAdminUserSession());
			m.addAttribute("adminIds",this.getGameUserIds());
			
			//移除掉agentid = 0 的ids
			List<String> idstrs = new ArrayList<String>();
			for(Long id : this.getGameUserIds()){
				idstrs.add(id.toString());
			}
			List<UserInfoDto> dtos = userInfoDao.queryUserInfos(idstrs);
			for(UserInfoDto u : dtos){
				if(u.getAgentId() == null || u.getAgentId().equals(0L)){
					idstrs.remove(u.getUserId().toString());
				} 
			}
			m.addAttribute("adminIdsDisplay",idstrs);
			
			userIds = this.getGameUserIds();
		}else{
			userIds = getUserIdsByAdmin(userId);
			if(!userIds.isEmpty()){
                AdminUserDto adminUserDto = adminUserService.queryByIdOrAccount(userId);
                m.addAttribute("adminUser",adminUserDto);
                m.addAttribute("adminIds",adminUserDto.getUserIds());
                
                //移除掉agentid = 0 的ids
                if(adminUserDto.getUserIds() != null && adminUserDto.getUserIds().split(",").length > 0){
                	List<String> idstrs = new ArrayList<String>();
        			
        			for(String id : adminUserDto.getUserIds().split(",")){
        				idstrs.add(id.toString());
        			}
        			List<UserInfoDto> dtos = userInfoDao.queryUserInfos(idstrs);
        			for(UserInfoDto u : dtos){
        				if(u.getAgentId() == null || u.getAgentId().equals(0L)){
        					idstrs.remove(u.getUserId().toString());
        				} 
        			}
        			m.addAttribute("adminIdsDisplay",idstrs);
                }
            }
		}
		if(null == userIds || userIds.isEmpty()){
			m.addAttribute("noResrlt",true);
			return "admin/finance/score/scoreProfile";
		}
		String ownSum = userManagerDao.queryOwnChargeSumByIds(userIds, sd, ed);
		String ownCount = userManagerDao.queryOwnChargeSumByIdsCount(userIds, sd, ed);
		String playerSum =userManagerDao.queryPlayerChargeSumByIds(userIds, sd, ed);
		String agentSum = userManagerDao.queryAgentChargeSumByIds(userIds, sd, ed);
		m.addAttribute("ownSum",ownSum);
		m.addAttribute("ownCount",ownCount);
		m.addAttribute("playerSum",playerSum);
		m.addAttribute("agentSum",agentSum);

		return "admin/finance/score/scoreProfile";
	}
	
	@RequestMapping("score/loadOwnDetail")
	public String scoreLoadOwnDetail(String userId,String sd,String ed,Integer page,Integer pageSize,Model m){

		List<Long> ids = null;
		if(StringUtil.isBlank(userId)){
			ids = this.getGameUserIds();
		}else{
			ids = getUserIdsByAdmin(userId);
		}
		
		PageDto pd = new PageDto(page,pageSize);
		List<UserPayDetailDto> result = payRecordDao.queryUsersPayDetail(ids,sd,ed,pd.getPageIndex(),pd.getPageSize());
		Integer count = payRecordDao.queryUsersPayDetailCount(ids,sd,ed);
		pd.setRecordCount(count);
		m.addAttribute("page",pd);
		
		m.addAttribute("queryResult",result);
		return "admin/finance/score/myPayList";
	}
	
	@RequestMapping("score/loadPlayerDetail")
	public String scoreLoadOwnDetail(@RequestParam(required=false)String userId,
			@RequestParam(required=false)Integer page,
			String sd,String ed,
			@RequestParam(required=false)Integer pageSize,Model m){
		List<Long> ids = null;
		PageDto pd = new PageDto(page,pageSize);
		if(StringUtil.isBlank(userId)){
			ids = this.getGameUserIds();
		}else{
			ids = getUserIdsByAdmin(userId);
		}
		List<PlayerInfoDto> list = userManagerDao.queryUserPlayer(null,sd,ed,ids,pd.getPageIndex(),pd.getPageSize());
		Integer count = userManagerDao.queryUserPlayerCount(null,sd,ed,ids);
		m.addAttribute("data",list);
		pd.setRecordCount(count);
		m.addAttribute("page",pd);
		return "admin/finance/score/playerDetail";
	}
	@RequestMapping("score/loadAgentDetail")
	public String scoreLoadAgentDetail(@RequestParam(required=false)String userId, Long agentId,
			@RequestParam(required=false)Integer page,
			String sd,String ed,
			@RequestParam(required=false)Integer pageSize,Model m){
		List<MyAgentDto> list = null;
		Integer count = null;
		PageDto pd = new PageDto(page,pageSize);
		if(null!=agentId){
			//这个查询是要用agentId查询
			list = userManagerDao.queryUserAgent(null,agentId,sd,ed,null,pd.getPageIndex(),pd.getPageSize());
			count = userManagerDao.queryUserAgentCount(null,agentId,sd,ed,null);
		}else{
			List<Long> ids = null;
			if(StringUtil.isBlank(userId)){
				ids = this.getGameUserIds();
			}else {
				ids = getUserIdsByAdmin(userId);
			}
			list = userManagerDao.queryUserAgentByIds(null,sd,ed, ids,null, pd.getPageIndex(), pd.getPageSize());
			count = userManagerDao.queryUserAgentByIdsCount(null,sd,ed, ids,null);
		}
		m.addAttribute("data",list);
		pd.setRecordCount(count);
		m.addAttribute("page",pd);
		return "admin/finance/score/myAgentList";
	}
	
	@RequestMapping("userfinanceList")
	public String userfinanceList(Long userId,String sd,String ed,Model m){
		
		
		List<PlayerInfoDto> list = userManagerDao.queryUserPlayerById(userId);
		PlayerInfoDto dto = null;
		if(list != null && !list.isEmpty()){
			dto = list.get(0);
		}
		
		if(dto == null){
			return "admin/finance/profile";
		}
		
		dto.setMyPayCount(payRecordDao.queryUserPayCount(dto.getUserId(),sd,ed));
		dto.setTotalCount(payRecordDao.queryUserPayCountCount(dto.getUserId(),sd,ed));
		dto.setMyPlayerPayCount(payRecordDao.queryUserPlayerPayCount(dto.getAgentId(),sd,ed));
		dto.setMyAngentPayCount(payRecordDao.queryUserAngentPayCount(dto.getAgentId(),sd,ed));
		m.addAttribute("sd",sd);
		m.addAttribute("ed",ed);
		m.addAttribute("userData",dto);
		return "admin/finance/profile";
	}
	
	@RequestMapping("userfinanceList/myPayList")
	public String userfinanceListmyPayList(Long userId,String sd,String ed,Integer page,Integer pageSize,Model m){
		PageDto pd = new PageDto(page,pageSize);
		List<UserPayDto> result = null;
		result = payRecordDao.queryUserPayDetail(userId,sd,ed,pd.getPageIndex(),pd.getPageSize());
		Integer count = payRecordDao.queryUserPayDetailCount(userId,sd,ed);
		pd.setRecordCount(count);
		m.addAttribute("page",pd);
		
		m.addAttribute("queryResult",result);
		return "admin/finance/myPayList";
	}
	
	@RequestMapping("userfinanceList/myPalayerList")
	public String userfinanceListmyPalayer(Long userId,Long agentId,String sd,String ed,Integer page,Integer pageSize,Model m){
		PageDto pd = new PageDto(page,pageSize);
		
		List<UserPayDto> result = payRecordDao.queryUserPlayerPayDetail(agentId,sd,ed,pd.getPageIndex(),pd.getPageSize());
		Integer count = payRecordDao.queryUserPlayerPayDetailCount(agentId,sd,ed);
		pd.setRecordCount(count);
		m.addAttribute("page",pd);
		m.addAttribute("queryResult",result);
		return "admin/finance/myPlayerList";
	}
	
	@RequestMapping("userfinanceList/myAgentList")
	public String userfinanceListmyAgentList(Long userId,Long agentId,String sd,String ed,Integer page,Integer pageSize,Model m){
		PageDto pd = new PageDto(page,pageSize);
		
		List<UserPayDto> result = payRecordDao.queryUserAngentPayDetail(agentId,sd,ed,pd.getPageIndex(),pd.getPageSize());
		Integer count = payRecordDao.queryUserAngentPayDetailCount(agentId,sd,ed);
		//上级ID没有查询出来，再这里填充进去
		for(UserPayDto dto : result){
			dto.setGroupId(userId);
		}
		
		pd.setRecordCount(count);
		m.addAttribute("page",pd);
		m.addAttribute("group_userId",userId);
		m.addAttribute("group_agentId",agentId);
		m.addAttribute("queryResult",result);
		return "admin/finance/myAgentList";
	}

	private List<Long> getUserIdsByAdmin(String seachStr){
		List<Long> ret = new ArrayList<>();
		AdminUserDto adminUserDto = adminUserService.queryByIdOrAccount(seachStr);
		if (null == adminUserDto) {
			return ret;
		}
		if(StringUtil.isNotBlank(adminUserDto.getUserIds())){
			ret = Arrays.stream(adminUserDto.getUserIds().split(",")).map(Long::parseLong).collect(Collectors.toList());
		}
		return ret;
	}

	@RequestMapping("dayReport")
	public String dayReportIndex(Model model){
		LocalDate today = LocalDate.now();
		model.addAttribute("startDate", today.with(TemporalAdjusters.firstDayOfMonth()));
		model.addAttribute("endDate", today);
		return "admin/finance/dayReport";
	}

	@RequestMapping("dayReportList")
	public String dayReportList(SqlParameterDto sqlParameterDto, Model model){
		PageDto pd = new PageDto(sqlParameterDto.getPage(), sqlParameterDto.getPageSize());
		sqlParameterDto.setPage(pd.getPageIndex());
		sqlParameterDto.setPageSize(pd.getPageSize());
		Long count = adminFeeReportService.queryDayFeeReportCount(sqlParameterDto);
		List<FeeReportDto> list = adminFeeReportService.queryDayFeeReport(sqlParameterDto);
		sqlParameterDto.setPageSize(null);
		sqlParameterDto.setPageSize(null);
		List<FeeReportDto> listAll = adminFeeReportService.queryDayFeeReport(sqlParameterDto);
		model.addAttribute("data",list);
		pd.setRecordCount(count.intValue());
		model.addAttribute("page",pd);
		model.addAttribute("pageFeeSum",adminFeeReportService.sumFee(list));
		model.addAttribute("allFeeSum",adminFeeReportService.sumFee(listAll));
		return "admin/finance/dayReportList";
	}

	@RequestMapping("monthReport")
	public String monthReport(Model model){
		LocalDate today = LocalDate.now();
		model.addAttribute("startDate", today.with(TemporalAdjusters.firstDayOfMonth()));
		model.addAttribute("endDate", today);
		return "admin/finance/monthReport";
	}

	@RequestMapping("monthReportList")
	public String monthReportList(SqlParameterDto sqlParameterDto, Model model){
		PageDto pd = new PageDto(sqlParameterDto.getPage(), sqlParameterDto.getPageSize());
		sqlParameterDto.setPage(pd.getPageIndex());
		sqlParameterDto.setPageSize(pd.getPageSize());
		Long count = adminFeeReportService.queryMonthFeeReportCount(sqlParameterDto);
		List<FeeReportDto> list = adminFeeReportService.queryMonthFeeReport(sqlParameterDto);
		sqlParameterDto.setPageSize(null);
		sqlParameterDto.setPageSize(null);
		List<FeeReportDto> listAll = adminFeeReportService.queryDayFeeReport(sqlParameterDto);
		model.addAttribute("data",list);
		pd.setRecordCount(count.intValue());
		model.addAttribute("page",pd);
		model.addAttribute("pageFeeSum",adminFeeReportService.sumFee(list));
		model.addAttribute("allFeeSum",adminFeeReportService.sumFee(listAll));
		return "admin/finance/monthReportList";
	}

	@RequestMapping("queryPayDetail")
	public String queryPayDetail(Model model){
		return "admin/finance/queryPayDetail";
	}

	@RequestMapping("queryPayDetailList")
	public String queryPayDetailList(SqlParameterDto sqlParameterDto, Model model){
		PageDto pd = new PageDto(sqlParameterDto.getPage(), sqlParameterDto.getPageSize());
		sqlParameterDto.setPage(pd.getPageIndex());
		sqlParameterDto.setPageSize(pd.getPageSize());
		Long count = payRecordDao.queryPayDetailCount(sqlParameterDto);
		List<UserPayDetailDto> list = payRecordDao.queryPayDetail(sqlParameterDto);
		model.addAttribute("data",list);
		pd.setRecordCount(count.intValue());
		model.addAttribute("page",pd);
		return "admin/finance/queryPayDetailList";
	}
	
}
